<?php
class pContentAction extends pBaseAction{

    // 二维数组来保存东西---表单中

    //授权栏目的id串
    protected $popedomCategories;

    public function _initialize(){
        $usr = $_SESSION[C('user_auth_key')];
        if(in_array($usr['role']['name'],C('admin_role'))){ //是系统管理员，对所有栏目有操作权限
            $this->popedomCategories = "all";
        }else{
            $prefix = C('db_prefix');
            $uid = $usr['user']['id'];

            $dao = get_instance_of('CategoryModel');
            $popedomCategories = $dao->field('category')->table("{$prefix}category_user")->where("userid={$uid}")->findAll();
            $ids = array();
            foreach($popedomCategories as $row){
                $ids[] = $row['category'];
            }
            $this->popedomCategories =implode(',',$ids);
        }
    }

    /**
     * 返回查询时的栏目过滤串
     */
    private function getCategoriesFilter($alias='',$fieldName='category'){
        return $alias.'.'.(('all' == $this->popedomCategories) ? $fieldName.'>0' : "{$fieldName} in ({$this->popedomCategories})");
    }

    public function index(){
        $dbPrefix = C('db_prefix');
        //search condition process
        $queryCond = array();
        if(array_key_exists('category',$_GET)){     //category cond
            $queryCond[] = '@category='.$_GET['category'];  // @ represent the table prefix
        }

        $dao = new Model();
        $cond = $this->getCategoriesFilter('m','many')." and m.lft ='post' and m.rgt='category'";
        $count = $dao->where($cond)->table("{$dbPrefix}one2many m")->count('distinct one');
        if($count>0){
            require LIB_PATH.'Util/PageEx.class.php';
            $p = new PageEx($count,12);
            $this->assign('list',$dao->field('p.id,p.title,p.created,u.account poster,p.status,p.thumb,group_concat(c.name) typename,group_concat(c.id) typeid')
                                     ->table("{$dbPrefix}one2many m")
                                     ->join("{$dbPrefix}category c on c.id=m.many")
                                     ->join("{$dbPrefix}post p on p.id=m.one")
                                     ->join("{$dbPrefix}user u on u.id=p.userid")
                                     ->limit($p->firstRow.','.$p->listRows)
                                     ->group('p.id desc')
                                     ->where($cond)
                                     ->findAll()
                            );
            $this->assign('page',$p->show());
        }
        $this->display();
    }

    /**
     * 添加文档
     *
     * 文档和模型挂钩，但暂时不过多考虑这个
     */
    public function add(){
        $dao = new CategoryModel();
        $categories = $dao->getTree();
        array_shift($categories);   //将数组开头的“顶级栏目”移出
        $this->assign('allocateCategories',$categories);
        $this->assign('popedomCategories',$this->popedomCategories);
        $this->display();
    }

    private function prepareData($postDao){
        $vo = $postDao->create();
        if(false === $vo) return false;
        $one2many = array();
        //取栏目数据
        $categoryIds = array();
        if(array_key_exists('category',$_POST)){
            $category = $_POST['category'];
            if(is_array($category)){
                if( 'all' === $this->popedomCategories){
                    foreach($category as $cat){
                        $one2many[] = array('many'=>$cat,'lft'=>'post','rgt'=>'category');
                        $categoryIds[] = $cat;
                    }
                }else{
                    $pc = split(',',$this->popedomCategories);
                    foreach($category as $cat){
                        if(in_array($cat,$pc)){
                            $one2many[] = array('many'=>$cat,'lft'=>'post','rgt'=>'category');
                            $categoryIds[] = $cat;
                        }
                    }
                }
            }
        }
        //准备tag信息
        $tagIds = array();
        if(array_key_exists('tags',$_POST)){
            //convert to array-json
            $tags = json_decode($_POST['tags'],TRUE);      //TODO 没有检测是否存在重复的tag
            $tagDao = get_instance_of('TagModel');
            foreach($tags as $tag){
                $tagname = trim($tag['name']);
                if(false === empty($tagname)){
                    $tagId = empty($tag['id']) ? $tagDao->getTagId($tagname) : $tag['id'];
                    $tagIds[] = $tagId;
                    $one2many[] = array('many'=>$tagId,'lft'=>'post','rgt'=>'tag');
                }
            }
        }

        //摘要
        if(empty($vo['summary'])){
            $vo['summary']=summary($vo['content'],220);
        }

        return array('postVo'=>$vo,'one2many'=>$one2many,'tagIds'=>implode(',',$tagIds),'categoryIds'=>implode(',',$categoryIds));
    }

    /**
     * 后置处理，保存完数据后做一些更新处理
     */
    private function after($vo){
        //tag的更新信息
        $tagIds = $vo['tagIds'];
        if(!empty($tagIds)){
            if(false === get_instance_of('TagModel','updateTagNums',array($tagIds))){
                return false;
            }
        }
        //更新栏目的使用计数
        $categoryIds = $vo['categoryIds'];
        if(!empty($categoryIds)){
            if(false === get_instance_of('CategoryModel','updateCategoriesNum',array($categoryIds))){
                return false;
            }
        }
        //meta信息
        if(array_key_exists('meta',$_POST)){
            $metaDao = get_instance_of('PostMetaModel');
            $postId = $vo['postVo']['id'];
            foreach($_POST['meta'] as $meta){
                //key为空则不存储
                if( false === empty($meta['key']) &&
                    false === $metaDao->add(array('post'=>$postId,'meta'=>$meta['key'],'value'=>$meta['value']))
                   ){
                       return false;
                }
            }
        }
        return true;
    }


    /**
     * 暂时忽略审核功能
     */
    public function save(){
        $dao = get_instance_of('PostModel');
        $dao->startTrans();
        $vo = $this->prepareData($dao);
        if(false === $vo){
            $this->simpleReturn($dao,false);
        }
        $postVo = $vo['postVo'];
        $postVo['status'] = 'publish'; //temp TODO
        $postVo['userid'] = $_SESSION[C('user_auth_key')]['user']['id'];
        $postId = $dao->add($postVo);
        if(false === $postId){
            $dao->rollback();
            $this->simpleReturn($dao,false);
        }
        $vo['postVo']['id'] = $postId;
        //保存one2many信息
        $one2manyDao = get_instance_of('One2manyModel');
        if(false === $one2manyDao->addAll($vo['one2many'],$postId)){
            $dao->rollback();
            $this->simpleReturn($one2manyDao,false);
        }
        if(false === $this->after($vo)){
            $dao->rollback();
            $this->simpleReturn($dao,false);
        }
        $dao->commit();
        $ret = array();
        $ret['id'] = $postId;   //$postid;
        $ret['audit'] = false;  //$this->checkAudit($postId);     //审核检查
        $ret['msg'] = ('draft' === $postVo['status']) ? L('module_savedraft_ok') : L('module_publish_ok');
        $ret['auditmsg'] = false ? L('module_has_audit') :L('module_without_audit');
        $this->ajaxReturn($ret,'',true);
    }

    public function edit(){
        $id = $this->getId('post');
        if(false === $id){
            $this->fail(L('module_edit_post_fail'),L('module_no_post_user'));   //TODO 语言变量未添加
        }
        //查找栏目、tag信息
        $dbPrefix = C('db_prefix');
        $one2manyDao = get_instance_of('One2manyModel');
        $this->assign('categoryVo',$one2manyDao->field('many')->where("one={$id} and lft='post' and rgt='category'")->select());
        $tagVo = $one2manyDao->field("t.id,t.name")
                             ->where("m.one={$id} and m.lft='post' and m.rgt='tag'")
                             ->table("{$dbPrefix}one2many m")
                             ->join("{$dbPrefix}tag t on t.id=m.many")->select();
        $this->assign('tagVo',$tagVo);
        //查找meta信息
        $metaDao = get_instance_of('PostMetaModel');
        $metaVo = $metaDao->where("post={$id}")->select();
        //查找post
        $dao = get_instance_of('PostModel');
        $vo = $dao->where("id={$id}")->find();
        $this->assign('post',$vo);
        $this->assign('metaVo',$metaVo);
        $this->assign('one2manyVo',$one2manyVo);

        $categories = get_instance_of('CategoryModel','getTree');
        array_shift($categories);   //将数组开头的“顶级栏目”移出
        $this->assign('allocateCategories',$categories);
        $this->assign('popedomCategories',$this->popedomCategories);

        $this->display();
    }

    /**
     * 更新文档...ajax方式进行
     */
    public function update(){
        $dao = get_instance_of('PostModel');
        $dao->startTrans();
        $vo = $this->prepareData($dao);
        if(false === $vo){
            $this->simpleReturn($dao,false);
        }
        $postVo = $vo['postVo'];
        //$postVo['userid'] = $_SESSION[C('user_auth_key')]['user']['id'];
        if(false === $dao->where("id={$postVo['id']}")->save($postVo)){ //更新实体
            $dao->rollback();
            $this->simpleReturn($dao,false);
        }
        $postId = $vo['postVo']['id'];
        //删除post的相关信息
        if(false === $this->deletePostRelatedInfo($postId)){
            $dao->rollback();
            $this->simpleReturn($one2manyDao,false);
        }
        //保存one2many信息
        $one2manyDao = get_instance_of('One2manyModel');
        if(false === $one2manyDao->addAll($vo['one2many'],$postId)){
            $dao->rollback();
            $this->simpleReturn($one2manyDao,false);
        }
        if(false === $this->after($vo)){
            $dao->rollback();
            $this->simpleReturn($dao,false);
        }
        $dao->commit();
        $ret = array();
        $ret['id'] = $postId;// $postid;
        $ret['audit'] = false; //$this->checkAudit($postId);     //审核检查
        $ret['msg'] = ('draft' === $postVo['status']) ? L('module_savedraft_ok') : L('module_publish_ok');
        $ret['auditmsg'] = false ? L('module_has_audit') :L('module_without_audit');
        $this->ajaxReturn($ret,'',true);
    }

    /**
     * 删除文档的相关信息，包括Tag、Category、和meta，并且更新相关的计数器
     * @param unknown_type $postId
     * @return unknown_type
     */
    private function deletePostRelatedInfo($postId){
        $prefix = C('db_prefix');
        //处理one2many中的tag、category等信息
        $one2manyDao = get_instance_of('One2manyModel');
        $rs = $one2manyDao->field('many,rgt')->where("one={$postId} and lft='post'")->select();
        if(false === empty($rs)){
            if(false === $one2manyDao->where("one={$postId} and lft='post'")->delete()) return false;
            $tags = array();
            $categories = array();
            foreach($rs as $row){
                switch ($row['rgt']){
                    case 'tag' : $tags[] = $row['many'];break;
                    case 'category' : $categories[] = $row['many'];break;
                }
            }
            //更新计数器
            if(false === empty($tags)){
                $tagDao = get_instance_of('TagModel');
                if(false === $tagDao->updateTagNums( implode(',',$tags),'-' )) return false;
            }
            if(false === empty($categories)){
                $categoryDao = get_instance_of('CategoryModel');
                if(false === $categoryDao->updateCategoriesNum( implode(',',$categories),'-' )) return false;
            }
        }
        //处理meta信息
        $metaDao = get_instance_of('PostMetaModel');
        if(false === $metaDao->where("post={$postId}")->delete()) return false;
        return true;
    }

    /**
     * 删除文档，支持单条（GET）或多条删（POST）
     * 暂时只做单条删除，而不做多条
     */
    public function removal(){
        $ret = array();
        $ret['msg'] = L('module_removal_fail');
        $postId = $this->getId('post');
        if(false === $postId){
            $dao->rollback();
            $this->ajaxReturn($ret,null,false);
        }
        $dao = get_instance_of('PostModel');
        $dao->startTrans();
        if(false === $this->deletePostRelatedInfo($postId)){
            $dao->rollback();
            $this->ajaxReturn($ret,null,false);
        }
        if(false === $dao->where("id={$postId}")->delete()){
            $dao->rollback();
            $this->ajaxReturn($ret,null,false);
        }
        $dao->commit();
        $ret['msg'] = L('module_removal_ok');
        $this->ajaxReturn($ret,null,true);
    }

    public function audit(){

    }

    /**
     * 检查审核权限，如果没有审核通过且当前用户有审核权限，则将予以审核通过
     *
     * @return boolean 审核信息
     */
    private function checkAudit($postid){
        $dao = get_instance_of('PostModel');
        if($dao->checkAudit($postid)){
            return true;
        }else{
            if(testAccess(MODULE_NAME,'audit')){    //拥有审核权限，则进行审核操作
                return $dao->auditPost($postid);
            }
            return false;
        }
    }

}
